const path = require('path');

const express = require('express');
const mongoose = require('mongoose');

const errorController = require('./controllers/error');
const User = require('./modules/user');

const app = express();

app.set('view engine', 'ejs');
app.set('views', 'views');

const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use((req, res, next) => {
    User.findById('62485c5a5db0164c6461160b')
    .then(user => {
        if(!user) {
            return User.create({
                name: 'tina',
                email: '123@qq.com',
                cart: {
                    items: []
                }
            })
        }
        return user;
    })
    .then(user => {
        req.user = user;
        next();
    })
    .catch(err => console.log(err))
})

app.use('/admin', adminRoutes);
app.use(shopRoutes);

app.use('/', errorController.get404);

mongoose.connect('mongodb+srv://root:RssOydxK5FtfwSC2@cluster0.9t1f0.mongodb.net/shop?retryWrites=true&w=majority')
.then(result => {
    console.log('数据库已连接');
    app.listen(443);
})